﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace MostRecentlyUsed
{
    /// <summary>
    /// Handles encryting and decrypting connection strings ready for persistent storage
    /// </summary>
    public class Encryption : MostRecentlyUsed.Interfaces.IEncryption
    {
        private string _vikey = "@1B2c3D4e5F6g7H8";

        /// <summary>
        /// Password Hash
        /// </summary>
        public string PasswordHash { get; set; } = "P@@Sw0rd";

        /// <summary>
        /// Salt key
        /// </summary>
        public string SaltKey { get; set; } = "S@LT&KEY";

        /// <summary>
        /// Encrypts the specified string using the <see cref="PasswordHash"/>, <see cref="SaltKey"/> and <see cref="vikey"/> provided
        /// </summary>
        /// <param name="plainText">Value to encrypt</param>
        /// <returns>Encrypted connection strings</returns>
        public string Encrypt(string plainText)
        {
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
            var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
            var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(_vikey));

            byte[] cipherTextBytes;

            using (var memoryStream = new MemoryStream())
            {
                using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                    cryptoStream.FlushFinalBlock();
                    cipherTextBytes = memoryStream.ToArray();
                }
            }

            return Convert.ToBase64String(cipherTextBytes);
        }

        /// <summary>
        /// Decrypts the specified string using the <see cref="PasswordHash"/>, <see cref="SaltKey"/> and <see cref="vikey"/> provided
        /// </summary>
        /// <param name="encryptedText">Value to decrypt</param>
        /// <returns>Decrypted connection strings</returns>
        public string Decrypt(string encryptedText)
        {
            byte[] cipherTextBytes = Convert.FromBase64String(encryptedText);
            byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
            var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };

            var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(_vikey));
            var memoryStream = new MemoryStream(cipherTextBytes);
            var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];

            int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
            memoryStream.Close();
            cryptoStream.Close();
            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
        }
    }
}